<?php
namespace app\common\model;
use think\Db;
use think\Model;
use think\Cookie;

class Base extends Model
{

    protected static function init()
    {
        // 事件，全局数据更新后记录日志
        // 模型事件只可以在调用模型的方法才能生效，使用查询构造器通过Db类操作是无效的
      /*  self::event('after_update', function ($model) {
            $data["uid"] = 1;
            $data["create_time"] = time();
            $data["update_time"] = time();
            $data["ip"] = '127.0.0.1';
            $data["behavior"] = 'after_update';
            $data["behavior"] = 'after_update';
            $data["description"] = '修改之后';
            $model->name('system_log')->insert($data);
        });*/
    }

    public function saveData($data){

        $save  = $this->allowField(true)->save($data);
        if ( $save == 0 || $save == false) {
            $res=[  'code'=> 1001,  'msg' => '数据保存失败', ];
        }else{
            $res=[  'code'=> 1000,  'msg' => '数据保存成功',  ];
        }
        return $res;
    }

    /**
     * 根据有Id修改信息 无Id 新增信息
     * @param $data
     * @return data
     */
    public function editData($data){
        if (isset($data['id'])){
            if (is_numeric($data['id']) && $data['id']>0){
                $id = $data['id'];
                $save = $this->allowField(true)->save($data,[ 'id' => $data['id']]);
            }else{
                $save  = $this->allowField(true)->save($data);
                $id = $this->getLastInsID();
            }
        }else{
            $save  = $this->allowField(true)->save($data);
            $id = $this->getLastInsID();
        }
        if ( $save == 0 || $save == false) {
            $res=[  'code'=> 1009,  'msg' => '数据更新失败', 'id' => $id];
        }else{
            $res=[  'code'=> 1001,  'msg' => '数据更新成功', 'id' => $id];
        }
        return $res;
    }

    /**
     * 通过查询条件获取单条数据对象--Db类
     */
    public function getInfosByMapWithDb($map=[],$field=true,$order='',$name){
        if(empty($order)){
            $neworder = 'id desc';
        }else{
            $neworder = $order;
        }
        $object_list = Db::name($name)->where($map)->field($field)->order($neworder)->paginate();
        return $object_list;
    }

    public function getCntByMapWithDb($map=[],$name){

        $object_list = Db::name($name)->where($map)->count('id');
        return $object_list;
    }

    public function getTotalsByMapWithDb($map=[],$field='id',$name){
        $object_list = Db::name($name)->where($map)->sum($field);
        return $object_list;
    }

    /**
     * 通过查询条件获取单条数据对象
     * @param array $map  查询条件
     * @param bool|true $field 字段
     * @param array $append 追加已经定义获取器字段
     * @param bool|true $status
     * @return $this|array|false|\PDOStatement|string|Model
     */
    public function getInfoByMap($map=[],$field=true,$append=[],$status=false){
        if(empty($map)){ $map = []; }
        if($status&&!isset($map['status'])){
            $map['status']=1;
        }
        $object = $this->where($map)->field($field)->find();
        if(!empty($object)&&!empty($append)){
            return $object->append($append);
        }else{
            return $object;
        }
    }

    /**
     * 通过查询条件获取多条数据(对象)
     * @param bool|true $field
     * @param bool|true $status
     * @return array
     */
    public function getInfosByMap($map=[],$field=true,$status=true,$order=''){
        if(empty($map)){ $map = []; }
        if($status&&!isset($map['status'])){
            $map['status']=1;
        }
        if(empty($order)){
            $neworder = 'id desc';
        }else{
            $neworder = $order;
        }

        $object_list = $this->where($map)->field($field)->order($neworder)->paginate();
        return $object_list;
    }

    /**
     * 通过查询条件获取多条数据(对象)
     * @param bool|true $field
     * @param bool|true $status
     * @return array
     */
    public function getInfosByMapLimit($map=[],$field=true,$status=true,$order='',$limit){
        if(empty($map)){ $map = []; }
        if($status&&!isset($map['status'])){
            $map['status']=1;
        }
        if(empty($order)){
            $neworder = 'id desc';
        }else{
            $neworder = $order;
        }

        $object_list = $this->where($map)->field($field)->order($neworder)->paginate($limit);
        return $object_list;
    }

    /**
     * 通过查询条件获取单条数据(数组)
     * @param array $map
     * @param bool|true $field
     * @param array $append
     * @param bool|true $status
     * @return array
     */
    public function getArrayByMap($map=[],$field=true,$append=[],$status=true){
        if(empty($map)){ $map = []; }
        if($status&&!isset($map['status'])){
            $map['status']=1;
        }

        $object = $this->where($map)->field($field)->find();

        if(!empty($object)&&!empty($append)){
            $return = $object->append($append);
        }else{
            $return = $object;
        }
        return empty($return) ? [] : $return->toArray();
    }


    /**
     * 通过查询条件获取多条数据(数组)
     * @param bool|true $field
     * @param array $append 这需要在模型里增加获取器
     * @param bool|true $status
     * @return array
     */
    public function getListByMap($map=[],$field=true,$append=[],$status=true){
        if(empty($map)){ $map = []; }
        if($status&&!isset($map['status'])){
            $map['status']=1;
        }

        $object_list = $this->where($map)->field($field)->select();
        $list=[];
        if(!empty($object_list)){
            foreach($object_list as $item=>$value){
                if(!empty($append)){
                    $list[]= $value->append($append)->toArray();
                }else{
                    $list[]= $value->toArray();
                }
            }
        }
        return $list;
    }

    public function getListByMapAndOrder($map=[],$field=true,$append=[],$status=true,$order=''){
        if(empty($map)){ $map = []; }
        if($status&&!isset($map['status'])){
            $map['status']=1;
        }
        if(empty($order)){
            $neworder = 'id desc';
        }else{
            $neworder = $order;
        }

        $object_list = $this->where($map)->field($field)->order($neworder)->select();
        $list=[];
        if(!empty($object_list)){
            foreach($object_list as $item=>$value){
                if(!empty($append)){
                    $list[]= $value->append($append)->toArray();
                }else{
                    $list[]= $value->toArray();
                }
            }
        }
        return $list;
    }


    /**
     * 通过查询条件获取数据总条数
     * @param array $map
     * @param bool|true $status
     * @return int
     */
    public function countNum($map=[],$status=true)
    {
        if(empty($map)){ $map = []; }
        if($status&&!isset($map['status'])){
            $map['status']=1;
        }
        $count = $this->where($map)->count();
        return $count;
    }


    /**
     * 获取无限极分类数据
     * @param array $data 这需要无限极分类的数据
     * @return array
     */
    public function sort($data,$parent_id=0){

        static $tree = array();
        foreach ($data as $k => $v) {
            if($v['parent_id']==$parent_id){
                $v['dataid'] = $this->getParentId($v['id']);
                $tree[] = $v;
                $this->sort($data,$v['id']);
            }
        }

        return $tree;
    }


    // 查询id和父级id
    public function getParentId($authRuleId){
        $authRuleRes = $this->select();

        return $this->_getParentId($authRuleRes,$authRuleId,True);
    }

    public function _getParentId($authRuleRes,$authRuleId,$clear=false){

        static $arr = array();
        if($clear){
            $arr = array();
        }
        foreach ($authRuleRes as $k => $v) {
            if($v['id']==$authRuleId){
                $arr[] = $v['id'];
                $this->_getParentId($authRuleRes,$v['parent_id'],False);
            }
        }
        $arr2 = array_reverse($arr);
        $arrstr = implode('-',$arr2);
        return $arrstr;
    }

}